<?php
namespace Go\Controller;
use Think\Controller;
ignore_user_abort(true);
set_time_limit(0);

class SendController extends Controller{
	
	/**
 	  type  1 邮件
	  type  2 手机
	  type  3 邮件,手机
	*/
	public function send_shop_code(){
		if(!isset($_POST['send']) && !isset($_POST['uid']) && !isset($_POST['gid'])){
			exit(0);
		}
		$uid = abs($_POST['uid']);
		$gid = abs($_POST['gid']);
		$db = new \Think\Model();
		$sendinfo = $db->query("SELECT id,send_type FROM `__PREFIX__send` WHERE `gid` = '$gid' and `uid` = '$uid'");
		if(!empty($sendinfo))exit(0);
		$member = $db->query("SELECT * FROM `__PREFIX__users` WHERE `userId` = '$uid'");
		if(empty($member))exit(0);
		$member = current($member);
		$info = $db->query("SELECT id,q_user_code,q_end_time,title,q_user FROM `__PREFIX__shoplist` WHERE `id` = '$gid' and `q_uid` = '$uid'");
		if(empty($info))exit(0);
		$info = current($info);
		$username = get_user_name($member,'userName','all');
		$this->send_insert($uid,$gid,$username,$info['title'],-1);
		$type = C('SEND_TYPE');
		if(!$type)exit(0);
		$q_time = abs(substr($info['q_end_time'],0,10));
		
		while(time() < $q_time){
			sleep(5);
		}
		$ret_send = false;
		if($type==1){
			if(!empty($member['userEmail'])){
				send_email_code($member['userEmail'],$username,$uid,$info['q_user_code'],$info['title']);
				$ret_send = true;
			}
		}
		if($type==2){
			if(!empty($member['mobile'])){
				send_mobile_shop_code($member['userPhone'],$uid,$info['q_user_code']);
				$ret_send = true;
			}
		}
		
		if($type==3){
			if(!empty($member['userEmail'])){
				send_email_code($member['userEmail'],$username,$uid,$info['q_user_code'],$info['title']);
				$ret_send = true;
			}
			if(!empty($member['userPhone'])){
				send_mobile_shop_code($member['userPhone'],$uid,$info['q_user_code']);
				$ret_send = true;
			}
		}
		
		if($ret_send){
			$this->send_insert($uid,$gid,$username,$info['title'],$type);
		}
		exit(0);
	}
	
	private function send_insert($uid,$gid,$username,$shoptitle,$send_type){
		$db = new \Think\Model();
		$time=time();
		if($send_type == -1){
			$sql = "INSERT INTO `__PREFIX__send` (`uid`,`gid`,`username`,`shoptitle`,`send_type`,`send_time`) VALUES ";
			$sql.= "('$uid','$gid','$username','$shoptitle','$send_type','$time')";
			$db->execute($sql);
		}else{
			$db->execute("UPDATE `__PREFIX__send` SET `send_type` = '$send_type' WHERE `gid` = '$gid' and `uid` = '$uid'");
		}
	}
	
	public function send_code(){
		send_email_code('354575573@qq.com','nice172zzz',40,10000929,'恭喜您!!!');
	}
	
}